package L01;
//Day  9_12

import java.util.Timer;
import java.util.concurrent.PriorityBlockingQueue;

//定时器的实现
class MyTimer{

    private PriorityBlockingQueue<Task> queue=new PriorityBlockingQueue();

    private Object Wait=new Object ();

    class Worker extends Thread{
        @Override
        public void run () {
            while(true){
                try {
                    //take函数返回队列首task，并删除
                    Task task=queue.take ();
                    long curTime=System.currentTimeMillis ();
                    if(task.time>curTime){//任务的执行时间没有到
                        queue.put (task);//重新把任务塞回
                        synchronized (Wait){
                            Wait.wait (task.time-curTime);
                        }
                    }else {
                        task.run ();
                    }

                } catch (InterruptedException e) {
                    throw new RuntimeException (e);
                }
            }
        }
    }


    class Task implements Comparable<Task>{//类的实现快捷键 Alt+Insert
        private Runnable runnable;
        public long time;//任务执行的时间

        public Task (Runnable runnable, long after) {
            this.runnable = runnable;
            //此处储存的time是绝对时间
            this.time = System.currentTimeMillis ()+after;
        }

        public void run(){
            runnable.run ();
        }

        @Override
        public int compareTo (Task o) {
            //
            return (int)(this.time-o.time);
        }
    }


    public MyTimer(){
        Worker work=new Worker ();
        work.start ();

    }

    //Timer类提供一个创建任务的方法
    public void schedule(Runnable run,long after){
        Task t1=new Task (run,after);
        //offer是优先级队列的插入函数
        queue.offer (t1);

        synchronized (Wait){
            Wait.notify ();
        }

    }
}






public class L19 {
    public static void main (String[] args) {

        MyTimer timer=new MyTimer ();

        timer.schedule (new Runnable () {
            @Override
            public void run () {
                System.out.println ("1000");
            }
        },1000);

        timer.schedule (new Runnable () {
            @Override
            public void run () {
                System.out.println ("2000");
            }
        },2000);

        timer.schedule (new Runnable () {
            @Override
            public void run () {
                System.out.println ("3000");
            }
        },3000);

        System.out.println ("自定义定时器开始执行");

    }

}
